package com.browsesoft.htmlcomponent.field;

import org.w3c.dom.Element;
import javax.servlet.http.HttpServletRequest;
import com.browsesoft.ExtendElement;
import com.browsesoft.tools.*;

/**
 *
 * <p>Title: 签字日期字段处理器</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2004</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 1.0
 */
public class DateProcessor extends FieldValueProcessor
{
    /**
     * 日期的显示元素
     */
    private Element dateElement;

    public DateProcessor()
  {
  }

  /**
   * setFieldValue
   *
   * @param e Element
   * @param value String
   * @param request HttpServletRequest
   */
  public void setFieldValue(Element e, String value, HttpServletRequest request)
  {
    // 设置日期字段值
    if(this.hasImageElement(e)) {
      //清除日期显示内容
      Element de = this.getDateElement(e);
      de.getParentNode().removeChild(de);
    }
    //如果值不为空
    if(value != null && !value.equals("")) {
      String v = this.dateToString(value, this.dateElement);
      ExtendElement.replaceElementContext(this.dateElement, v);
      e.getParentNode().appendChild(this.dateElement.cloneNode(true));
    }
    //设置隐藏域值
    e.setAttribute("value", value);
  }

  /**
   * 是否有日期元素
   */
  private boolean hasImageElement(Element e) {
    Element parent = (Element)e.getParentNode();
    String name = e.getAttribute("name");
    return ExtendElement.findElements(parent, "elementname", name).size() != 0;
  }

  /**
   * 转换日期值
   */
  private String dateToString(String value, Element e) {
    BSCalendar c = new BSCalendar(value, "yyyymmddhhttss");
    String format = e.getAttribute("timeformat");
    return c.toString(format);
  }

  /**
   * 设置配置元素
   */
  public void setConfig(Element config) {
    super.setConfig(config);
    this.dateElement = (Element) this.getDateElement(config).cloneNode(true);
  }

  /**
   * 得到日期元素
   */
  private Element getDateElement(Element e) {
    Element parent = (Element)e.getParentNode();
    String name = e.getAttribute("name");
    return (Element)ExtendElement.findElements(parent, "elementname", name).get(0);
  }

  /**
   * 只读处理什么也不作即可
   */
  public void setReadOnly(Element e, String value)
  {
  }
  }
